import { Button, Row, Col } from 'antd';
import type { MqttClient } from 'mqtt';
import { useEffect, useRef } from 'react';
import mqtt from 'mqtt';

const Lib01 = () => {
  const client = useRef<MqttClient | null>(null);

  const publish = () => {
    client.current!.publish('test', 'Hello MQTT');
  };
  const subscribe = () => {
    client.current!.subscribe('test');
  };

  useEffect(() => {
    console.log('bb');
    client.current = mqtt.connect('ws://localhost:8083');
    client.current!.on('connect', () => {
      console.log('已连接服务器');
      // // 订阅主题
      // client.current!.subscribe('test');
      // // 发布测试消息
      // client.current!.publish('test', 'Hello MQTT');
    });

    client.current!.on('message', (topic, message) => {
      console.log(`收到消息: ${topic} -> ${message}`);
    });
    return () => {
      console.log('aa');
      client.current!.end(true);
    };
  }, []);
  return (
    <div>
      <h1>Lib01</h1>
      <Row>
        <Col>
          <Button onClick={publish}>发送测试消息</Button>
        </Col>
        <Col>
          <Button onClick={subscribe}>订阅主题</Button>
        </Col>
      </Row>
    </div>
  );
};
export default Lib01;
